/* A simple server in the internet domain using TCP
   The port number is passed as an argument */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "bhtpdvpls_structs.h"
#include "pslsimfunc.h"
#include "socket_header.h"
#include <opencv/cv.h>
#include <opencv/highgui.h>


int main(int argc, char *argv[])
{
    struct sockaddr_in serv_addr, cli_addr;

    if (argc < 2)
    {
        fprintf(stderr,"ERROR, no port provided\n");
        exit(1);
    }

    int16_t portno 	= atoi(argv[1]);
    int sockfd 		= socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        error("ERROR opening socket");

    memset((void *)&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family 	= AF_INET;
    serv_addr.sin_addr.s_addr 	= INADDR_ANY;
    serv_addr.sin_port 		= htons(portno);
    if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR on binding");
    listen(sockfd,5);

    IplImage * cambild = cvCreateImage( cvSize( 640, 480 ), 8, 3 );
    CvFont font;
    double hScale=1.0;
    double vScale=1.0;
    int    lineWidth=1;
    cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth);

    while (1)
    {
        printf("Wating to connect\n");
        int clilen = sizeof(cli_addr);
        int newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, (socklen_t*)(&clilen));
        if (newsockfd < 0)
            error("ERROR on accept");
        else
            printf("Connected\n");

        int i= 0;
        while (1)
        {

            char buffer[256];
            sprintf(buffer, "%04d", i++);
            cvSet(cambild, CV_RGB(0,0,0));
            cvPutText (cambild, buffer, cvPoint(200,400), &font, cvScalar(255,255,0));

            ComandPkg command;
	    char cmdbuffer[5] = {0};
            int n  = readin(newsockfd, cmdbuffer,  4);
            if (n == 0)
            {
                printf("Disconnected\n");
                break;
            }
            printf("recv %s\n", cmdbuffer);
            ObjektListe objekte;
            
            objekte.kord[0].objektId = 0;
            objekte.kord[0].xkordinate_mm = 100;
            objekte.kord[0].ykordinate_mm = 150;
            objekte.kord[0].theta_grad = 200;
            objekte.anzahlObjekte = 1;
            
//            switch (command.cmd)
//            {
//            case OBJECTS_REQUEST:
                n   = send(newsockfd, (char*)&objekte,  sizeof(ObjektListe), 0);
                
                n  += send(newsockfd, (char*)cambild,   sizeof(IplImage),    0);
                n  += send(newsockfd, (char*)(cambild->imageData),  cambild->imageSize,    0);
                if (n == 0)
                {
                    printf("Disconnected\n");
                    break;
                }
//                break;
//
//            default:
//                //TODO: Fehler abfangen
//                break;
//            }
        }
    }

    close(sockfd);
    return 0;
}
